#ifndef _THREAD_H_
#define _THREAD_H_

#include <pthread.h>
#include <unistd.h>
#include <functional>
#include <string>
#include <iostream>
#include"Log.hpp"

using namespace LogModule;

namespace ThreadModel
{
    static uint32_t number = 1;
    class thread
    {
        using func_t = std::function<void ()>;

        void EnableRunning() { _isrunning = true; }
        void EnableDetach() { _isdetach = true; }

        //需要与ptherad_create的参数匹配void*(void*)不能设为成员函数，因为成员函数有this指针
        static void *Routine(void *args)
        {
            // 线程执行流起始点
            thread *self = static_cast<thread *>(args);
            self->EnableRunning();
            // 创建时分离
            if (self->_isdetach)
                self->Detach();
            pthread_setname_np(self->_tid, self->_name.c_str()); 
            //调用任务
            self->_func();

            // 线程终止
            return nullptr;
        }

    public:
        thread(const func_t &func)
            : _tid(0), _res(nullptr), _func(func), _isdetach(false), _isrunning(false)
        {
            _name = "thread-" + std::to_string(number);
            number++;
        }

        void Detach()
        {
            if (!_isrunning)
                return;

            // 随时分离
            if (!_isdetach)
            {
                pthread_detach(_tid);
                EnableDetach();
            }
        }

        bool start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n != 0)
            {
                return false;
            }
            else
            {
                LOG(LogLevel::INFO)<<"创建了一个新线程name:"<<_name;
            }
            return true;
        }

        bool stop()
        {
            if (!_isrunning)
                return false;
            // 在主线程中终止对象线程
            int n = pthread_cancel(_tid);
            if (n != 0)
            {
                return false;
            }
            else
            {
                _isrunning=false;
                LOG(LogLevel::INFO)<<_name<<"线程终止了";
            }
            return true;
        }

        bool join()
        {
            if (!_isrunning&&!_isdetach)
                return false;

            // 等待线程并输出返回值
            int n = pthread_join(_tid, &_res);
            if (n != 0)
            {
                return false;
            }
            else
            {
                LOG(LogLevel::INFO)<<"Join到了"<<_name<<"线程";
            }
            return true;
        }

    private:
        pthread_t _tid;
        std::string _name;
        void *_res;
        func_t _func;
        bool _isdetach;
        bool _isrunning;
    };
};

#endif